package cn.tedu.ttms.reflect;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
/**
 * @Retention 用于定义注解何时有效
 * @Target 用于定义注解应用于什么元素上
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Autowired{}

class  Student{
    @Autowired
    int age;
    String name;

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

public class TestReflect {
    public static void main(String[] args) throws IllegalAccessException {
        Student s = new Student();
        /*获取类对象*/
        Class clazz = s.getClass();
        /*获得Student类中所有属性*/
        Field[] field = clazz.getDeclaredFields();
        for (Field f:field) {
            /*判断f属性是否使用了AutoWired注解修饰*/
            if(f.isAnnotationPresent(Autowired.class)){
                /*设置私有属性可访问*/
                f.setAccessible(true);
                //位s对象的f属性赋值
                f.set(s,18);
            }

        }
        System.out.println(s);
    }
}
